#include "tcpserver.hpp"
#include "protocal.hpp"
#include <memory>

using namespace tcpserver;

void Usage(string str)
{
    std::cerr<<"Usage:\n\tstr"<<" port\n\n";
}

bool cal(const Request &req, Response &resp)
{
    // req已经有结构化完成的数据啦，你可以直接使用
    resp.exitcode = OK;
    resp.result = OK;

    switch (req.op)
    {
    case '+':
        resp.result = req.x + req.y;
        break;
    case '-':
        resp.result = req.x - req.y;
        break;
    case '*':
        resp.result = req.x * req.y;
        break;
    case '/':
    {
        if (req.y == 0)
            resp.exitcode = DIV_ZERO;
        else
            resp.result = req.x / req.y;
    }
    break;
    case '%':
    {
        if (req.y == 0)
            resp.exitcode = MOD_ZERO;
        else
            resp.result = req.x % req.y;
    }
    break;
    default:
        resp.exitcode = OP_ERROR;
        break;
    }

    return true;
}


void calculate(connection* conn)
{   
    string OnePackage;
    while(ParseOnePackage(conn->_inbuffer,&OnePackage))
    {
        //一定拿到一个完整的报文
        string resStr;
        //去报头
        if(!deLength(OnePackage,&resStr))
            return;
        //反序列化
        Request req;
        if(!req.deserialize(resStr))    return;
        //完成上层应用逻辑
        Response resp;
        cal(req,resp);
        string respStr;
        //序列化
        resp.serialize(&respStr);
        //加报头
        conn->_outbuffer += enLength(respStr);
        std::cout << "------result: " << conn->_outbuffer << std::endl;
    }
    if (conn->_sender)
        conn->_sender(conn);
}

int main(int argc,char* argv[])
{
    if(argc != 2)
    {
        Usage(argv[0]);
    }
    uint16_t port = atoi(argv[1]);
    unique_ptr<Tcpserver> tsvr(new Tcpserver(calculate,port));
    tsvr->InitServer();
    tsvr->Dispatcher();
    return 0;
}